package com.apikey.auth.controller;

import com.apikey.auth.entity.History;
import com.apikey.auth.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 历史记录控制器
 * 提供API Key变更历史查询接口
 *
 * @author API Key Framework
 * @version 1.0
 */
@RestController
public class HistoryController {

    @Autowired
    private HistoryService historyService;

    /**
     * 分页查询历史记录 - 新增的搜索接口
     *
     * @param page       页码，从0开始
     * @param size       每页大小
     * @param sort       排序字段
     * @param direction  排序方向
     * @param apiKeyId   API Key ID过滤
     * @param operatorId 操作者ID过滤
     * @param operation  操作类型过滤
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @return 分页结果
     */
    @GetMapping("/api/history/search")
    public ResponseEntity<Map<String, Object>> searchHistoryRecords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "updatedAt") String sort,
            @RequestParam(defaultValue = "desc") String direction,
            @RequestParam(required = false) Long apiKeyId,
            @RequestParam(required = false) String operatorId,
            @RequestParam(required = false) String operation,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {

        Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction) ? Sort.Direction.DESC : Sort.Direction.ASC;
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));

        Page<History> history = historyService.findHistory(null, operatorId, operation, startTime, endTime, pageable);

        Map<String, Object> response = new HashMap<>();
        response.put("content", history.getContent());
        response.put("totalElements", history.getTotalElements());
        response.put("totalPages", history.getTotalPages());
        response.put("currentPage", history.getNumber());
        response.put("size", history.getSize());
        response.put("first", history.isFirst());
        response.put("last", history.isLast());

        return ResponseEntity.ok(response);
    }

    /**
     * 获取操作类型统计信息
     *
     * @return 操作类型统计
     */
    @GetMapping("/history/operation-type-stats")
    public ResponseEntity<Map<String, Object>> getOperationTypeStats() {
        try {
            List<Map<String, Object>> operationStats = historyService.getOperationTypeStats();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", operationStats);
            response.put("message", "获取操作类型统计成功");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取操作类型统计失败: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 分页查询历史记录
     *
     * @param page       页码，从0开始
     * @param size       每页大小
     * @param sort       排序字段
     * @param direction  排序方向
     * @param apiKeyId   API Key ID过滤
     * @param operatorId 操作者ID过滤
     * @param operation  操作类型过滤
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @return 分页结果
     */
    @GetMapping("/api/history")
    public ResponseEntity<Map<String, Object>> getHistory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "operationTime") String sort,
            @RequestParam(defaultValue = "desc") String direction,
            @RequestParam(required = false) Long apiKeyId,
            @RequestParam(required = false) String operatorId,
            @RequestParam(required = false) String operation,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {

        Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction) ?
                Sort.Direction.DESC : Sort.Direction.ASC;
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));

        Page<History> history = historyService.getHistory(
                apiKeyId, operatorId, operation, startTime, endTime, pageable);

        Map<String, Object> response = new HashMap<>();
        response.put("content", history.getContent());
        response.put("totalElements", history.getTotalElements());
        response.put("totalPages", history.getTotalPages());
        response.put("currentPage", history.getNumber());
        response.put("size", history.getSize());

        return ResponseEntity.ok(response);
    }

    /**
     * 根据API Key ID查询历史记录
     *
     * @param apiKeyId API Key ID
     * @param page     页码
     * @param size     每页大小
     * @return 分页结果
     */
    @GetMapping("/by-apikey/{apiKeyId:[0-9]+}")
    public ResponseEntity<Map<String, Object>> getHistoryByApiKey(
            @PathVariable Long apiKeyId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "operationTime"));
        Page<History> history = historyService.getHistory(apiKeyId, null, null, null, null, pageable);

        Map<String, Object> response = new HashMap<>();
        response.put("content", history.getContent());
        response.put("totalElements", history.getTotalElements());
        response.put("totalPages", history.getTotalPages());
        response.put("currentPage", history.getNumber());
        response.put("size", history.getSize());

        return ResponseEntity.ok(response);
    }

    /**
     * 根据操作者ID查询历史记录
     *
     * @param operatorId 操作者ID
     * @param page       页码
     * @param size       每页大小
     * @return 分页结果
     */
    @GetMapping("/by-operator/{operatorId:.+}")
    public ResponseEntity<Map<String, Object>> getHistoryByOperator(
            @PathVariable String operatorId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "updatedAt"));
        Page<History> history = historyService.getHistory(null, operatorId, null, null, null, pageable);

        Map<String, Object> response = new HashMap<>();
        response.put("content", history.getContent());
        response.put("totalElements", history.getTotalElements());
        response.put("totalPages", history.getTotalPages());
        response.put("currentPage", history.getNumber());
        response.put("size", history.getSize());

        return ResponseEntity.ok(response);
    }

    /**
     * 根据操作类型查询历史记录
     *
     * @param operation 操作类型
     * @param page      页码
     * @param size      每页大小
     * @return 分页结果
     */
    @GetMapping("/by-operation/{operation:.+}")
    public ResponseEntity<Map<String, Object>> getHistoryByOperation(
            @PathVariable String operation,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "updatedAt"));
        Page<History> history = historyService.getHistory(null, null, operation, null, null, pageable);

        Map<String, Object> response = new HashMap<>();
        response.put("content", history.getContent());
        response.put("totalElements", history.getTotalElements());
        response.put("totalPages", history.getTotalPages());
        response.put("currentPage", history.getNumber());
        response.put("size", history.getSize());

        return ResponseEntity.ok(response);
    }

    /**
     * 根据时间范围查询历史记录
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param page      页码
     * @param size      每页大小
     * @return 分页结果
     */
    @GetMapping("/by-time-range")
    public ResponseEntity<Map<String, Object>> getHistoryByTimeRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "updatedAt"));
        Page<History> history = historyService.getHistory(null, null, null, startTime, endTime, pageable);

        Map<String, Object> response = new HashMap<>();
        response.put("content", history.getContent());
        response.put("totalElements", history.getTotalElements());
        response.put("totalPages", history.getTotalPages());
        response.put("currentPage", history.getNumber());
        response.put("size", history.getSize());

        return ResponseEntity.ok(response);
    }

    /**
     * 搜索历史记录
     *
     * @param keyword 关键字
     * @param page    页码
     * @param size    每页大小
     * @return 分页结果
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchHistory(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Page<History> history = historyService.searchHistory(keyword, page, size);

        Map<String, Object> response = new HashMap<>();
        response.put("content", history.getContent());
        response.put("totalElements", history.getTotalElements());
        response.put("totalPages", history.getTotalPages());
        response.put("currentPage", history.getNumber());
        response.put("size", history.getSize());

        return ResponseEntity.ok(response);
    }

    /**
     * 获取历史记录统计信息
     *
     * @return 统计信息
     */
    @GetMapping("/api/history/stats")
    public ResponseEntity<Map<String, Object>> getHistoryStats() {
        try {
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusDays(30);

            Map<String, Object> stats = new HashMap<>();
            stats.put("totalOperations", historyService.getTotalOperationCount());
            stats.put("todayOperations", historyService.getTodayOperationCount());
            stats.put("operationDistribution", historyService.getOperationDistribution(startTime, endTime));
            stats.put("topOperators", historyService.getTopOperators(10));

            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            Map<String, Object> errorStats = new HashMap<>();
            errorStats.put("totalOperations", 0);
            errorStats.put("todayOperations", 0);
            errorStats.put("operationDistribution", new HashMap<>());
            errorStats.put("topOperators", new java.util.ArrayList<>());
            return ResponseEntity.ok(errorStats);
        }
    }

    /**
     * 获取操作类型分布统计
     *
     * @return 操作类型分布
     */
    @GetMapping("/stats/operation-distribution")
    public ResponseEntity<Map<String, Object>> getOperationDistribution() {
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(30);
        Map<String, Object> distribution = historyService.getOperationDistribution(startTime, endTime);
        return ResponseEntity.ok(distribution);
    }

    /**
     * 获取热门操作者统计
     *
     * @param limit 返回数量限制
     * @return 热门操作者列表
     */
    @GetMapping("/stats/top-operators")
    public ResponseEntity<List<Map<String, Object>>> getTopOperators(
            @RequestParam(defaultValue = "10") int limit) {
        List<Map<String, Object>> topOperators = historyService.getTopOperators(limit);
        return ResponseEntity.ok(topOperators);
    }

    /**
     * 获取每日操作统计
     *
     * @param days 统计天数
     * @return 每日统计列表
     */
    @GetMapping("/stats/daily")
    public ResponseEntity<List<Map<String, Object>>> getDailyOperationStats(
            @RequestParam(defaultValue = "7") int days) {
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(days);
        List<Map<String, Object>> dailyStats = historyService.getDailyOperationStats(startTime, endTime);
        return ResponseEntity.ok(dailyStats);
    }

    /**
     * 获取API Key变更趋势
     *
     * @param days 统计天数
     * @return 变更趋势数据
     */
    @GetMapping("/stats/change-trend")
    public ResponseEntity<List<Map<String, Object>>> getChangeTrend(
            @RequestParam(defaultValue = "30") int days) {
        List<Map<String, Object>> changeTrend = historyService.getChangeTrend(days);
        return ResponseEntity.ok(changeTrend);
    }

    /**
     * 导出历史记录
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param format    导出格式（csv/excel）
     * @return 导出文件
     */
    @GetMapping("/export")
    public ResponseEntity<String> exportHistory(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            @RequestParam(defaultValue = "csv") String format) {

        String exportData = historyService.exportHistory(format, null, null, null, startTime, endTime);
        return ResponseEntity.ok(exportData);
    }

    /**
     * 获取最近的历史记录
     *
     * @param limit 限制数量，默认10条
     * @return 最近的历史记录列表
     */
    @GetMapping("/api/history/recent")
    public ResponseEntity<List<History>> getRecentHistory(
            @RequestParam(defaultValue = "10") int limit) {

        try {
            Pageable pageable = PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "operationTime"));
            Page<History> historyPage = historyService.getHistory(null, null, null, null, null, pageable);

            return ResponseEntity.ok(historyPage.getContent());
        } catch (Exception e) {
            // 返回空列表而不是错误，避免前端显示异常
            return ResponseEntity.ok(new java.util.ArrayList<>());
        }
    }

    /**
     * 获取历史记录详情
     *
     * @param id 历史记录ID
     * @return 历史记录详情
     */
    @GetMapping("/{id:[0-9]+}")
    public ResponseEntity<History> getHistoryDetail(@PathVariable Long id) {
        History history = historyService.findById(id);
        if (history != null) {
            return ResponseEntity.ok(history);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 比较两个历史记录版本
     *
     * @param id1 第一个历史记录ID
     * @param id2 第二个历史记录ID
     * @return 比较结果
     */
    @GetMapping("/compare/{id1:[0-9]+}/{id2:[0-9]+}")
    public ResponseEntity<Map<String, Object>> compareHistory(
            @PathVariable Long id1,
            @PathVariable Long id2) {
        Map<String, Object> comparison = historyService.compareHistory(id1, id2);
        return ResponseEntity.ok(comparison);
    }

    /**
     * 清理历史记录
     *
     * @param days 保留天数
     * @return 清理结果
     */
    @DeleteMapping("/api/history/cleanup")
    public ResponseEntity<Map<String, Object>> cleanupHistory(
            @RequestParam(defaultValue = "90") int days) {

        try {
            int deletedCount = historyService.cleanupOldHistory(days);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("deletedCount", deletedCount);
            response.put("message", "清理完成");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "清理失败: " + e.getMessage());

            return ResponseEntity.badRequest().body(response);
        }
    }
}